import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Message } from 'element-ui'
import qs from 'qs'

const request = axios.create({
  // 配置选项
  // baseURL,
  // timeout
})

let isRefreshingToken = false
let requestConfigs: object[] = []

function redirectLogin () {
  router.push({
    name: 'login',
    query: {
      redirect: router.currentRoute.fullPath
    }
  })
}

function refreshToken () {
  isRefreshingToken = true
  axios({
    method: 'POST',
    url: '/front/user/refresh_token',
    headers: { Authorization: store.state.user.access_token },
    data: qs.stringify({
      refreshtoken: store.state.user.refresh_token
    })
  })
    .then(res => {
      if (!res.data.success) {
        Message.error('刷新TOKEN失败')
        redirectLogin()
      }
      store.commit('setUser', res.data.content)
      requestConfigs.forEach(config => {
        request(config)
      })
      requestConfigs = []
    })
    .catch(err => {
      console.log(err)
      store.commit('setUser', null)
      redirectLogin()
    })
    .finally(() => {
      isRefreshingToken = false
    })
}

// Add a request interceptor
request.interceptors.request.use(function (config) {
  // Do something before request is sent
  if (store.state.user) {
    config.headers.Authorization = store.state.user.access_token
  }
  return config
}, function (error) {
  // Do something with request error
  return Promise.reject(error)
})

// Add a response interceptor
request.interceptors.response.use(function (response) {
  // Any status code that lie within the range of 2xx cause this function to trigger
  // Do something with response data
  return response
}, function (error) {
  // Any status codes that falls outside the range of 2xx cause this function to trigger
  // Do something with response error
  if (error.response) {
    const { status, config } = error.response
    if (status === 400) {
      Message.error('请求参数错误')
    } else if (status === 401) {
      if (!store.state.user) {
        redirectLogin()
      } else {
        requestConfigs.push(config)
        !isRefreshingToken && refreshToken()
      }
    } else if (status === 403) {
      Message.error('没有权限 请联系管理员')
    } else if (status === 404) {
      Message.error('请求资源不存在')
    } else if (status >= 500) {
      Message.error('服务器错误 请联系管理员')
    }
  } else if (error.request) {
    Message.error('请求失败')
  } else {
    Message.error(`请求失败 ${error.message || ''}`)
  }
  return Promise.reject(error)
})

export default request
